"""
用户账户向相关功能： 注册、短信、登录、注销
"""

from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from web.forms import account
from web import models
import uuid
import datetime


# 用户注册
def register(request):
    if request.method == 'POST':
        form = account.RegisterModeForm(request.POST)
        if form.is_valid():
            # 验证通过,数据库创建用户，密码要是密文
            instance = form.save()  # 会自动剔除 原数据库没有的字段,并产生一个用户对象
            # 为用户添加一个默认的交易记录
            price_policy_obj = models.PricePolicy.objects.filter(category=1).first()
            models.Transaction.objects.create(
                status=2,
                order=uuid.uuid4(),  # 随机字符串，唯一
                user=instance,
                price_policy=price_policy_obj,
                count=0,
                price=0,
                start_datetime= datetime.datetime.now(),
            )
            return JsonResponse({'status': True, 'url': '/login/'})
        else:
            return JsonResponse({'status': False, 'error': form.errors})
        #     return render(request, 'register.html', {'form': form})
        # else:
        #     errors = form.errors.get('__all__')
        #     return render(request, 'register.html', {'form': form, 'errors': errors})
    form = account.RegisterModeForm()
    return render(request, 'register.html', {'form': form})


# 发送短信
def send_sms(request):
    # 传入数据 ，验证手机号码是否合法
    form = account.SendSmsForm(request, data=request.GET)
    if form.is_valid():
        # 钩子全部验证通过 发送状态码给前端
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# 短信登陆

def login_sms(request):
    if request.method == 'POST':
        form = account.LoginSmsForm(request.POST)
        if form.is_valid():
            # 记录 session
            mobile_phone = form.cleaned_data.get('mobile_phone')
            user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)  # 设置session 超时时间
            return JsonResponse({'status': True, 'url': '/index/'})
        else:
            return JsonResponse({'status': False, 'error': form.errors})
    form = account.LoginSmsForm()
    return render(request, 'login_sms.html', {'form': form})


def login(request):
    """用户名或手机号登录"""
    form = account.LoginForm(request)
    if request.method == 'POST':
        form = account.LoginForm(request, data=request.POST)
        if form.is_valid():
            """验证成功，判断用户登录的账号和密码是否正确，邮箱或者手机号和密码是否匹配"""
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            from django.db.models import Q
            user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
                password=password
            ).first()
            if user_obj:
                request.session['user_id'] = user_obj.id
                request.session.set_expiry(60 * 60 * 24 * 14)  # 设置session 超时时间
                return redirect('/index/')
            form.add_error('username', '用户名或密码错误')
        return render(request, 'login.html', {'form': form})
    return render(request, 'login.html', {'form': form})


def get_image_code(request):
    """获取图片验证码 展示在前端"""
    from utils import get_image_code
    code = get_image_code.get_random_code_img(request)
    return HttpResponse(code)


# 首页信息
def index(request):
    return render(request, 'index.html')


# 用户注销
def logout(request):
    request.session.flush()
    return redirect('/index/')
